﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar.Metro;
using DevComponents.DotNetBar.Controls;
using PlanningGIS.Win.Controls;
using PlanningGIS.ManageUtility;
using PlanningGIS.ManageUtility.Modules;
using DevComponents.DotNetBar;
using DevComponents.AdvTree;
using PlanningGIS.ManageUtility.DataAccess;

namespace PlanningGIS.Manager
{
    /// <summary>
    /// 部门管理
    /// </summary>
    public partial class CtlDepartment : UserControl
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public CtlDepartment()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 当前操作的状态值：1新增；2修改；3删除；4拖动；0未知
        /// </summary>
        private int _OpValue = 0;

        /// <summary>
        /// 是否开始监听值的变化
        /// </summary>
        private bool _Listening = false;

        /// <summary>
        /// 当前值是否有改变
        /// </summary>
        private bool _Changed = false;

        /// <summary>
        /// 
        /// </summary>
        private BillCommands _Commands;
        
        /// <summary>
        /// Gets or sets the commands associated with the control.
        /// </summary>
        public BillCommands Commands
        {
            get { return _Commands; }
            set
            {
                if (value != _Commands)
                {
                    BillCommands oldValue = _Commands;
                    _Commands = value;
                    OnCommandsChanged(oldValue, value);
                }
            }
        }

        /// <summary>
        /// Called when Commands property has changed.
        /// </summary>
        /// <param name="oldCmd">Old property value</param>
        /// <param name="newCmd">New property value</param>
        protected virtual void OnCommandsChanged(BillCommands oldCmd, BillCommands newCmd)
        {
            btnSave.Command = newCmd != null ? newCmd.DepartmentCommands.Save : null;
            btnCancel.Command = newCmd != null ? newCmd.DepartmentCommands.Cancel : null;
        }

        /// <summary>
        /// 
        /// </summary>
        public void LoadControl()
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                _Listening = false;
                ClearText();
                RegValueEvent();
                txtName.Tag = null;
                _OpValue = 0;
                departmentTree.BindData();
                cmbDepartment.BindData();
                if (departmentTree.Nodes.Count == 0) btnAdd_Click(null, null);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }            
        }

        /// <summary>
        /// 监听文本输入框值是否改变
        /// </summary>
        public void RegValueEvent()
        {
            foreach (Control c in this.Controls)
            {
                if (c is TextBoxX)
                {
                    ((TextBoxX)c).TextChanged += Text_TextChanged;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Text_TextChanged(object sender, EventArgs e)
        {
            if (_Listening) _Changed = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void departmentTree_AfterNodeSelect(object sender, DevComponents.AdvTree.AdvTreeNodeEventArgs e)
        {
            if (_Changed)
            {
                DialogResult dlg = MsgHelper.ShowYesOrNoQueryMsgBox("当前值已修改，是否保存？");
                if (dlg == DialogResult.Yes)
                {
                    btnSave_Click(null, null);
                }
            }            
            if (e.Node == null || e.Node.Tag == null) return;
            _Listening = false;
            Department d = (Department)e.Node.Tag;
            txtName.Tag = e.Node;
            txtName.Text = d.Name.Trim();            
            txtNotes.Text = d.Notes.Trim();            
            cmbDepartment.SetSelectValue(d.Parent_ID);
            _OpValue = 2;
            _Listening = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void departmentTree_BeforeNodeDrop(object sender, TreeDragDropEventArgs e)
        {
            DialogResult dlg = MsgHelper.ShowYesOrNoQueryMsgBox("是否修改部门节点层级？");
            if (dlg != DialogResult.Yes)
            {
                e.Cancel = true;
                return;
            }
            //if (e.Node.Tag == null && !(departmentTree.SelectedNode.Tag is Department)) return;
            try
            {
                Department d = (Department)e.Node.Tag;
                if (e.NewParentNode == null) d.Parent_ID = "";
                else d.Parent_ID = ((Department)e.NewParentNode.Tag).ID;
                int cnt = ManageHelper.DBContext.Update<Department>(d, "id", d.ID, false);
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox(ex.ToString());
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void departmentTree_AfterNodeDrop(object sender, TreeDragDropEventArgs e)
        {
           

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (departmentTree.SelectedNode == null)
            {
                btnAddRoot_Click(null, null);
                return;
            }
            _OpValue = 1;
            ClearText();
           cmbDepartment.SetSelectValue(((Department)departmentTree.SelectedNode.Tag).ID);
            _Listening = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddRoot_Click(object sender, EventArgs e)
        {
            _OpValue = 1;
            ClearText();
            cmbDepartment.SetSelectValue(cmbDepartment.DefaultID);
            txtName.Tag = null;
            _Listening = true;
        }

        /// <summary>
        /// 清除输入框中的信息
        /// </summary>
        private void ClearText()
        {
            foreach (Control c in this.Controls)
            {
                if (c is TextBoxX)
                {
                    ((TextBoxX)c).Text = "";
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (departmentTree.SelectedNode == null)
            {
                MsgHelper.ShowInfomationMsgbox("请先选择要删除的部门");
                return;
            }
            string msg = "是否确定要删除所选择的部门及其子部门信息？";
            DialogResult dlg = MsgHelper.ShowYesOrNoQueryMsgBox(msg);
            if (dlg != DialogResult.Yes) return;
            this.Cursor = Cursors.WaitCursor;
            try
            {
                Delete(departmentTree.SelectedNodes);
                for (int i = departmentTree.SelectedNodes.Count - 1; i >= 0; i--)
                {
                    departmentTree.SelectedNodes[i].Remove();
                }
                cmbDepartment.BindData();
                _Listening = false;
                _Changed = false;
                MsgHelper.ShowInfomationMsgbox("删除成功");
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("删除失败:" + ex.ToString());
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="nodes"></param>
        private void Delete(NodeCollection nodes)
        {
            foreach (Node nd in nodes)
            {
                if (nd.Nodes.Count > 0)
                {
                    Delete(nd.Nodes);
                }
                if (nd.Tag != null)
                {
                    DepartmentAccess.DeleteDepartment(((Department)nd.Tag).ID.Trim());
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtName.Text))
            {
                MsgHelper.ShowInfomationMsgbox("部门名称不能为空");
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            Department d = new Department()
            {
                ID = Guid.NewGuid().ToString(),
                Name = txtName.Text.Trim(),
                Notes = txtNotes.Text.Trim()
            };
            try
            {
                if (cmbDepartment.SelectedNode == null || cmbDepartment.SelectedNode.Tag == null) d.Parent_ID = "";
                else d.Parent_ID = ((Department)cmbDepartment.SelectedNode.Tag).ID;
                int cnt = 0;
                if (_OpValue == 1)
                {
                    cnt = ManageHelper.DBContext.Insert<Department>(d);
                }
                else if (_OpValue == 2)
                {
                    if (txtName.Tag == null)
                    {
                        MsgHelper.ShowErrorMsgbox("请先选择要修改的部门");
                        return;
                    }
                    string id = ((Department)(((Node)txtName.Tag).Tag)).ID;
                    cnt = ManageHelper.DBContext.Update<Department>(d, "id", id);
                }
                if (cnt < 1)
                {
                    MsgHelper.ShowErrorMsgbox("操作失败:" + ManageHelper.DBContext.Message);
                    return;
                }                          
                _OpValue = 0;
                _Listening = false;
                _Changed = false;
                departmentTree.BindData();
                cmbDepartment.BindData();      
                Node[] nds = departmentTree.Nodes.Find(d.ID, true);
                if (nds != null && nds.Length > 0) departmentTree.SelectedNode = nds[0];
                MsgHelper.ShowInfomationMsgbox("操作成功");
            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("操作失败:" + ex.ToString());
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (_Changed)
            {
                DialogResult dlg = MsgHelper.ShowYesOrNoQueryMsgBox("部门列表已变更，是否保存");
                if (dlg == DialogResult.Yes)
                {
                    btnSave_Click(null, null);
                }
            }
            _Changed = false;
            _Listening = false;
        }

    }
}
